package com.freshfresh.adapter;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ContentValues;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.freshfresh.activity.R;
import com.freshfresh.utils.FreshConstants;
import com.freshfresh.utils.ImageLoadOptions;
import com.freshfresh.utils.RequestManager;
import com.freshfresh.utils.UrlConstants;
import com.freshfresh.utils.Utils;
import com.freshfresh.view.db.DBManager;
import com.nostra13.universalimageloader.core.ImageLoader;

public class GridAdapter extends BaseAdapter {
	List<Map<String, Object>> apk_list;
	LayoutInflater inflater;
	Activity context;
    int i=1;
     String str_productid="";
     Dialog progressDialog;
	public GridAdapter(Activity context, List<Map<String, Object>> apk_list) {
		this.apk_list = apk_list;
		this.context=context;
		this.inflater = LayoutInflater.from(context);
		if (progressDialog == null) {
			progressDialog = Utils.createLoadingDialog(context,
					"正在处理中……");
		}
	}

	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return apk_list.size();
	}

	public void notifyData(List<Map<String, Object>> apk_list) {
		this.apk_list=apk_list;
		this.notifyDataSetChanged();
	}

	@Override
	public Object getItem(int position) {
		// TODO Auto-generated method stub
		return apk_list.get(position);
	}

	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub
		Map<String, Object> entity = apk_list.get(position);
		ViewHolder holder;
		if (convertView == null) {
			holder = new ViewHolder();
			convertView = inflater.inflate(R.layout.it_activitydetail, null);
			holder.iv_guoqi = (ImageView) convertView
					.findViewById(R.id.iv_guoqi);
			holder.iv_buy = (ImageView) convertView
			.findViewById(R.id.iv_buy);
			holder.img_icon = (ImageView) convertView
					.findViewById(R.id.img_icon);
			holder.tv_proName = (TextView) convertView
					.findViewById(R.id.tv_proName);
			holder.tv_guige = (TextView) convertView
					.findViewById(R.id.tv_guige);
			holder.tv_price = (TextView) convertView
					.findViewById(R.id.tv_price);
			holder.tv_price_orignal = (TextView) convertView
					.findViewById(R.id.tv_price_orignal);

			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}
		if (entity.get("national_flag") != null) {
			ImageLoader.getInstance().displayImage(
					entity.get("national_flag").toString(), holder.iv_guoqi,
					ImageLoadOptions.getOptions(R.drawable.guoqi));
		}

		if (entity.get("image") != null) {
			ImageLoader.getInstance().displayImage(
					entity.get("image").toString(), holder.img_icon,
					ImageLoadOptions.getOptions(0));
		}

		if (entity.get("name") != null) {
			holder.tv_proName.setText(entity.get("name").toString());
		}

		if (entity.get("standard2") != null) {
			holder.tv_guige.setText(entity.get("standard2").toString());
		}
		if (entity.get("special_price") != null) {
			holder.tv_price.setText("¥"+entity.get("special_price").toString());
		}
		if (entity.get("price") != null) {
			holder.tv_price_orignal.setText("¥"+entity.get("price").toString());
		}
		final int pos=position;
		holder.iv_buy.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				showDialog(pos);
			}
		});
		

		return convertView;
	}

	class ViewHolder {
		ImageView iv_guoqi;// 国旗
		ImageView iv_buy;//购物车
		ImageView img_icon;// 图片

		TextView tv_proName;// 名称
		TextView tv_guige;// 规格
		TextView tv_price;// 价格
		TextView tv_price_orignal;// 原价

	}
	
	public void showDialog(int pos){
		final Map<String, Object> entity = apk_list.get(pos);
		final AlertDialog.Builder builder = new AlertDialog.Builder(context);  
        final View textEntryView = inflater.inflate(  R.layout.dl_shoppingcar_dialog, null);  
        builder.setView(textEntryView);  
        final AlertDialog dialogs=builder.show();  
        //名称 
        LinearLayout rg_dialog_xuanze=(LinearLayout)textEntryView.findViewById(R.id.rg_dialog_xuanze);
        GridView gvs_type=(GridView)textEntryView.findViewById(R.id.gvs_type);
        ImageView dialog_title_image=(ImageView)textEntryView.findViewById(R.id.dialog_title_image);//图标
        
        ImageView iv_shoppingcar_add=(ImageView)textEntryView.findViewById(R.id.iv_shoppingcar_add);//添加
        ImageView iv_shoppingcar_reduction=(ImageView)textEntryView.findViewById(R.id.iv_shoppingcar_reduction);//减少
        
        final TextView ed_shoppingcar_show=(TextView)textEntryView.findViewById(R.id.ed_shoppingcar_show);
        TextView tv_standard1=(TextView)textEntryView.findViewById(R.id.tv_standard1);//下
        final TextView tv_dialog_standard=(TextView)textEntryView.findViewById(R.id.tv_dialog_standard);//上
        
        TextView dl_dialog_title_name=(TextView)textEntryView.findViewById(R.id.dl_dialog_title_name);
        dl_dialog_title_name.setText(entity.get("name").toString());
        if (entity.get("image") != null) {
			ImageLoader.getInstance().displayImage(entity.get("image").toString(), dialog_title_image,ImageLoadOptions.getOptions(0));
		}
        //价格
        TextView dl_dialog_title_price=(TextView)textEntryView.findViewById(R.id.dl_dialog_title_price);
        dl_dialog_title_price.setText("¥"+entity.get("special_price").toString());
        //判断多规格
        if(entity.get("type").toString().equals("simple")){
        	rg_dialog_xuanze.setVisibility(View.VISIBLE);
        	gvs_type.setVisibility(View.GONE);
        	tv_standard1.setText(entity.get("standard2").toString());
        	tv_dialog_standard.setText(entity.get("standard2").toString());
        	str_productid=entity.get("product_id").toString();
        }else if(entity.get("type").toString().equals("bundle")){
        	rg_dialog_xuanze.setVisibility(View.GONE);
        	gvs_type.setVisibility(View.VISIBLE);
        	final List<Map<String,Object>> listmap_guige=(List<Map<String,Object>>)entity.get("bundle_list");
        	final GuigeAdapter adapters=new GuigeAdapter(context, listmap_guige);
        	gvs_type.setAdapter(adapters);
        	if(listmap_guige!=null&&listmap_guige.size()!=0){
    		tv_dialog_standard.setText(listmap_guige.get(0).get("standard2").toString());
    		str_productid=listmap_guige.get(0).get("product_id").toString();
        	}
        	gvs_type.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1,
						int arg2, long arg3) {
					
					if(listmap_guige!=null&&listmap_guige.size()!=0){
			    		tv_dialog_standard.setText(listmap_guige.get(arg2).get("standard2").toString());
			    		adapters.setSeclection(arg2);
			    		adapters.notifyDataSetChanged();
			    		str_productid=listmap_guige.get(arg2).get("product_id").toString();
		        	}
				}
			});
        }
        
        Button btn_shoppingcar_info=(Button)textEntryView.findViewById(R.id.btn_shoppingcar_info);
        btn_shoppingcar_info.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				if(FreshConstants.hasLogined(context)){
					//已经登录了，添加购物车到服务器
					progressDialog.show();
					
					Map<String,String> map=new HashMap<String, String>();
					map.put("product_id", str_productid);
					map.put("bundle_id", "");
					map.put("qty", ed_shoppingcar_show.getText().toString());
					String str_listmap="["+Utils.map2json(map)+"]";
					
					
					SharedPreferences share=FreshConstants.getUserShared(context);
					 String userid=share.getString("userid", "");
					 String token=share.getString("token", "");
					
					Map<String, String> params = new HashMap<String, String>();
					params.put("store", "1");
					params.put("quoteid", "");
					params.put("token", token);
					params.put("customerid", userid);
					params.put("productsdata", str_listmap);
					
					
					Map<String,Object> map_obj=new HashMap<String, Object>();
					map_obj.put("customerid", userid);
					map_obj.put("store ", "1");
					map_obj.put("token ", token);
					map_obj.put("productsdata ", str_listmap);
					String str_mapobj=Utils.map2json(map_obj);
					
					params.put("cartProductAdd", str_mapobj);
					
					String ad_url = UrlConstants.AddShoppingCar;
					executeRequest(new StringRequest(ad_url, params,
							new Response.Listener<String>() {
								public void onResponse(String arg0) {
									progressDialog.dismiss();
									Log.e("listmap的……", arg0);
									if (Utils.parseJsonStr(arg0).get("result").toString().equals("1")) {
										Map<String,Object> map=(Map<String,Object>)Utils.parseJsonStr(arg0).get("data");
										String quoteidstr=map.get("quoteid").toString();
										SharedPreferences share=FreshConstants.getUserShared(context);
										share.edit().putString("quoteid", quoteidstr).commit();
										List<Map<String,Object>> listmap_serve=(List<Map<String,Object>>)map.get("product_info");
//										onDateChange(listmap_serve);
										Intent intent=new Intent(FreshConstants.ADD_SERVER_SHOPPINGCAR);
										intent.putExtra("list", (Serializable)listmap_serve);
										context.sendBroadcast(intent);
										Toast.makeText(context, "添加购物车成功", 1).show();
									} else {
										
									}
								}

							}, new Response.ErrorListener() {

								public void onErrorResponse(VolleyError arg0) {
									progressDialog.dismiss();
									Toast.makeText(context, "添加失败", 1).show();
								}
							}));
					dialogs.dismiss();
				}else{
					//没有登录，添加购物车到本地
					String[] columns = { "product_id","picurl", "name", "stock" ,"price","count"};
					String selection = "product_id" + "=?";
					String[] selectionArgs = { entity.get("product_id").toString() };
					Cursor cursor = DBManager.getDBconnection(context).query("fresh_shoppingcar", columns, selection, selectionArgs, null, null, null);
					
					String stock="";
					if(entity.get("is_in_stock").toString().equals("0")){
						stock="缺货";
					}else if(entity.get("is_in_stock").toString().equals("1")){
						stock="现货";
					}
					if (cursor != null && cursor.moveToFirst()) {
						//更新数据库
						Log.e("已经有该商品了", "已经有该商品了");
						String oldcounts = cursor.getString(cursor.getColumnIndex("count"));  //s是字段path的值
						if(oldcounts!=null){
							int newcount=Integer.parseInt(oldcounts)+i;
							UpdateShopCar(entity.get("product_id").toString(),entity.get("image").toString(), entity.get("name").toString(), stock, entity.get("special_price").toString(), newcount+"");
							Intent intent=new Intent(FreshConstants.LOCAL_SHOPPINGCARUPDATE);
							context.sendBroadcast(intent);
						}
					}else{
						//添加数据库
						ContentValues values = new ContentValues();
						values.put("product_id", entity.get("product_id").toString());
						values.put("picurl",entity.get("image").toString());
						values.put("name",entity.get("name").toString());
						values.put("stock",stock);
						values.put("price",entity.get("special_price").toString());
						values.put("count",i+"");
						DBManager.getDBconnection(context).insert("fresh_shoppingcar", null, values);
						Log.e("添加新商品", "添加新商品");
						Toast.makeText(context, "添加购物车成功", 0).show();
						
						Intent intent=new Intent(FreshConstants.LOCAL_SHOPPINGCAR);
						context.sendBroadcast(intent);
					}
					i=1;
					dialogs.dismiss();
				}
				
			}
		});
        ed_shoppingcar_show.setText(i+"");
        //
        iv_shoppingcar_add.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				i++;
				ed_shoppingcar_show.setText(i+"");
			}
		});
        iv_shoppingcar_reduction.setOnClickListener(new OnClickListener() {
        	@Override
        	public void onClick(View arg0) {
        		i--;
        		if(i<1){
        			i=1;
        			Toast.makeText(context, "该商品至少购买一件", 0).show();
        		}
        		ed_shoppingcar_show.setText(i+"");
		
			}
        });
        
	}
	
	 public int UpdateShopCar(String product_id,String picurl,String name,String stock,String price, String count){
	        SQLiteDatabase db =DBManager.getDBconnection(context);
	        ContentValues cv = new ContentValues();
	        cv.put("product_id", product_id);
	        cv.put("picurl", picurl);
	        cv.put("name", name);
	        cv.put("stock", stock);
	        cv.put("price", price);
	        cv.put("count", count);
	        String[] args = {String.valueOf(product_id)};
	        Toast.makeText(context, "添加购物车成功", 0).show();
	        return db.update("fresh_shoppingcar", cv, "product_id=?",args);    
	    }
	 
	 protected void executeRequest(Request request) {
			RequestManager.addRequest(request, this);
		}
}
